<template>
    <div>
        <el-dialog center class="global-dialog" v-model="dialogVisable" width="800px" top="10vh" :show-close="true"
            :close-on-click-modal="false" @close="close">
            <template #title>
                <div class="my-header" v-loading="detail_loading">
                    <el-tabs v-model="tabId" class="demo-tabs">
                        <el-tab-pane label="基本信息" name="1">
                            <el-form :model="diaForm" ref="DiaForm" :rules="rules" status-icon label-width="120px" status>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="软件名称" prop="name">
                                            <el-input placeholder="请输入" v-model="diaForm.name" style="width: 100%"
                                                clearable maxlength="40" show-word-limit   />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="首次发表日期" prop="firstPublicDate">
                                            <el-date-picker v-model="diaForm.firstPublicDate" type="date"
                                                value-format="YYYY-MM-DD" placeholder="选择日期" clearable
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="登记号" prop="registerNo">
                                            <el-input placeholder="请输入" v-model="diaForm.registerNo" style="width: 100%"
                                                clearable maxlength="40" show-word-limit  />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="维护单位" prop="maintainUnit">
                                            <popup-tree-input :data="orgAllList" :props="popupTreeProps" :prop="deptForm.parentName == null
                                                ? $t('message.org.top_menu')
                                                : diaForm.maintainUnit
                                                " :node-key="'' + deptForm.parentId"
                                                :current-change-handle="changeUnit" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="著作权人" prop="copyOwner">
                                            <el-input placeholder="请输入" v-model="diaForm.copyOwner" style="width: 100%"
                                                clearable maxlength="20" show-word-limit  />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="发证日期" prop="issueDate">
                                            <el-date-picker v-model="diaForm.issueDate" type="date"
                                                value-format="YYYY-MM-DD" placeholder="选择日期" clearable
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <!--                                        <el-form-item label="所属项目" prop="projectId">
                                            <el-select v-model="diaForm.projectId" filterable placeholder="请选择" style="width: 100%"
                                                @change="changeProgect"  clearable >
                                                <el-option :label="item.projectname" :value="item.id" :key="item.id"
                                                    v-for="item in projectList"  />
                                            </el-select>

                                        </el-form-item>-->
                                        <el-form-item label="所属项目" prop="projectName">
                                            <el-select v-model="diaForm.projectName" filterable placeholder="请选择"
                                                style="width: 80%" @change="changeProgect" clearable disabled>
                                                <el-option :label="item.projectname" :value="item.id" :key="item.id"
                                                    v-for="item in projectList1" />

                                            </el-select>
                                            <el-button type="primary" @click="open">选择</el-button>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="业务模块" prop="techClassId">
                                            <el-select v-model="diaForm.techClassId" clearable placeholder="请选择"
                                                style="width: 100%" @change="changeType">
                                                <el-option :label="el.itemText" :value="el.itemValue" :key="k"
                                                    v-for="(el, k) in technologyList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <!--  <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="软著状态" prop="softStateId">
                                            <el-select v-model="diaForm.softStateId" clearable placeholder="请选择"
                                                style="width: 100%" @change="changeState">
                                                <el-option :label="el.itemText" :value="el.itemValue" :key="k"
                                                    v-for="(el, k) in awardList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row> -->
                                <el-row :gutter="20">

                                    <el-col :span="12">

                                        <el-form-item label="合同中规定的成果" prop="isContractSuccess">
                                            <el-select v-model="diaForm.isContractSuccess" placeholder="请选择"
                                                style="width: 100%">
                                                <el-option :label="item.text" :value="item.value" :key="item.value"
                                                    v-for="item in options.isHightPayList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-form-item label="证书存放地" prop="saveAddress">

                                    <el-input v-model="diaForm.saveAddress" :autosize="{ minRows: 2, maxRows: 6 }"
                                        type="textarea" placeholder="请输入" clearable  maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="diaForm.remark" :autosize="{ minRows: 2, maxRows: 6 }"
                                        type="textarea" placeholder="请输入" maxlength="300" show-word-limit  />
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="相关附件" name="2">
                            <platformFiles :files="files" @filesParams="filesParams" download="KJSL:KJCG:RJZZQ:DOWNLOAD"
                                upload="KJSL:KJCG:RJZZQ:UPLOAD" fileDelete="KJSL:KJCG:RJZZQ:FILEDELETE"></platformFiles>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="close">关闭</el-button>
                    <el-button type="primary" @click="save">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <!-- 项目弹窗 -->
    <el-dialog v-model="Visible" width="900px" top="17vh" :show-close="false" :close-on-click-modal="false">
        <template #title>
            <div class="my-header">
                <el-tabs v-model="activeName" class="demo-tabs">
                    <el-tab-pane label="项目选择" name="first">
                        <div class="search-box">
                            <el-input v-model="xiangmuParams.projectName" placeholder="请输入" class="input-with-select"
                                style="width: 300px">
                                <template #append>
                                    <el-button type="primary" @click="open">搜索</el-button>
                                </template>
                            </el-input>
                        </div>
                        <el-table :data="options.xiangmuList" style="width: 100%" border
                            @selection-change="handleSelectionChange1">
                            <el-table-column type="selection" width="40" />
                          <el-table-column prop="projectName" label="项目名称" />
                          <el-table-column prop="projectNumber" label="项目编号" />
                          <el-table-column prop="departmentName" label="关联部门" />
                          <el-table-column prop="projectLeaderName" label="项目负责人" />
                          <el-table-column prop="projectYear" label="立项年份" />
                        </el-table>
                        <div class="example-pagination-block">
                            <el-pagination background layout="prev, pager, next ,total,sizes,jumper" :total="options.total"
                                :page-size="xiangmuParams.size" @current-change="handleCurrentChange"
                                @size-change="handleSizeChange" />
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <div class="handle">
                    <el-button color="#626aef" @click="Visible = false">关闭</el-button>
                    <el-button type="primary" @click="toHandle1">关联</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts">
import UserListModal from '@/views/project/components/UserListModal/index.vue';
import {
    addForm,
    editForm,
    getDetailById,
    getDictionary,
    getProject,
    getUnit, getUser
} from "@/views/science/api/achievements";
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import PlatformFiles from '@/views/science/components/platformFiles/platformFiles.vue';
import Record from '@/views/science/components/record/record.vue';
import { tips } from "@/views/science/components/tips/tips";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { projectManagementListPage } from "@/views/science/technologyStrength/api/technologyStrength";
import Api from "@/views/science/api/profess";

// import Work from './work';

export default {
    components: {
        PlatformFiles, Record, UserListModal, PopupTreeInput
    },
    props: {

        orgAllList: {
            type: Array,
            required: true,
        },
        dialogVisable: {
            type: Boolean,
            default: false,
        },

        // falg  1:新增  2:编辑  3:详情
        flag: {
            type: String,
            default: "1",
        },
        id: {
            type: String,
            default: '',
        },
        // initData: {
        //   type: Object,
        //   required: true,
        // },
        // initNum: {
        //   type: Object,
        // },
    },
    setup(props, { emit }) {
        let DiaForm = ref();
        // const tabId = ref('1')
        // watch(
        //     () => props.id,
        //     () => {
        //         console.log(props.id,"监听id变化")
        //         // 深度监听.只有在id存在的时候调用详情的接口
        //         if (props.id) {
        //             getDetail(props.id)
        //         }
        //     },
        //     { deep: true, immediate: true }
        // );
        watch(
            () => props.dialogVisable,
            () => {
                if (props.id) {
                    getDetail(props.id)
                }
            },
            { deep: true, immediate: true }

        );
        // 发送请求
        onMounted(() => {
            // 获取数据字典
            getUnitList();

            getWorkList()

            getProjectList()

            getCodeList()


        });

        const deptForm = {
            parentId: 0,
            parentName: '',
        }


        let data = reactive({
            popupTreeProps: {
                label: 'name',
                children: 'children',
            },
            tabId: '1',
            detail_loading: false,
            unitNameList: [],//维护单位
            workerList: [],//桌著作人
            technologyList: [],//技术分类
            awardList: [],//软著状态
            projectList1: [],//项目
            diaForm: {
                id: '',
                name: '',
                firstPublicDate: "",
                registerNo: '',
                maintainUnitId: '',
                maintainUnit: '',
                copyOwnerId: '',
                copyOwner: '',
                issueDate: '',
                projectId: '',
                project: '',
                projectname: '',
                projectName: '',
                projectleader: '',
                techClassId: '',
                techClass: '',
                softState: '',
                softStateId: '',
                saveAddress: '',
                remark: '',
                isContractSuccess: '',
            },
            files: [],
            changeLogs: [],

        });

        //清空form
        const clearForm = () => {
            data.diaForm.isContractSuccess = ''

        }

        // 弹窗中的选择
        let options = reactive({
            xiangmuList: [], //项目列表
            projectList: [],
            contractList: [],
            total: 0,
            isHightPayList: [
                { text: '否', value: '1', },
                { text: '是', value: '0', },
            ],
        })
        let Visible = ref(false)
        //项目搜索参数
        let xiangmuParams = reactive({
            projectName: '',
            projectNumber: '',
            createOrgId: '',
            level: '',
            current: 1,
            size: 10,
            projectCategory: '1',
        })
        //项目列表
        let open = async () => {
            const res = await projectManagementListPage(xiangmuParams)
            const rs = res.data.data
            options.xiangmuList = rs.records
            options.total = rs.total
            Visible.value = true
        }
        //改变页码
        const handleCurrentChange = (e) => {
            xiangmuParams.current = e
            open()
        }
        //改变页数限制
        const handleSizeChange = (e) => {
            xiangmuParams.size = e
            open()
        }
        let changeList = ref([])
        let activeName = ref('first')
        let isShow = ref(false)
        let isProject = ref(false)
        let select1 = ref([]) //项目

        let handleSelectionChange1 = (val) => {
            select1.value = val
        }
        const toHandle1 = () => {
            if (select1.value.length != 1) {
                tips('请选择一项关联', 'warning')
                return
            } else {
                let obj = select1.value[0]
                data.diaForm.projectId = (obj as any).id
                data.diaForm.projectName = (obj as any).projectName
                Visible.value = false
            }
        }
        Api.getProjectList().then((res) => {
            // console.log('项目列表', res.data.data)
            options.projectList = res.data.data
        })

        // 规则校验
        let rules = reactive({
            name: [
                { required: true, message: '请输入软件名称', trigger: 'blur' },
            ],
            firstPublicDate: [
                { required: true, message: '请选择首次发表日期', trigger: 'change', },
            ],
            maintainUnit: [
                { required: true, message: '请选择维护单位', trigger: 'change', },
            ],
            copyOwner: [
                { required: true, message: '请输入著作权人', trigger: 'change', },
            ],

            issueDate: [
                { required: true, message: '请选择发证日期', trigger: 'change', },
            ],
            projectName: [
                { required: true, message: '请选择所属项目', trigger: 'change', },
            ],
            techClassId: [
                { required: true, message: '请选择技术分类', trigger: 'change', },
            ],
            softStateId: [
                { required: true, message: '请选择软著状态', trigger: 'change' },
            ],
            isContractSuccess: [
                { required: true, message: '请输入合同中规定的成果', trigger: 'change', },
            ],

        });

        // 保存
        let save = () => {


            DiaForm.value.validate((valid) => {

                // 校验通过
                if (valid) {
                    //flag 1 新增  2 编辑  3  详情
                    if (props.flag == 1) {

                        data.diaForm.id = '';


                        addForm(
                            {
                                info: data.diaForm,
                                files: data.files,
                            }
                        ).then(() => {

                            tips("新增成功", "success");

                            DiaForm.value.resetFields();

                            emit("changeDialog", '1');

                        });


                    } else {
                        editForm({
                            info: data.diaForm,
                            files: data.files,
                        }).then(() => {

                            tips("编辑成功", "success");

                            DiaForm.value.resetFields();

                            emit("changeDialog", '1');

                        });

                    }
                } else {

                    return tips('请将基本信息补充完整', 'warning')

                }


            });
        }

        let succeedApproval = (item) => {
            console.log(item)
        }


        let filesParams = (params) => {

            data.files = params
        }

        let changeState = (id) => {

            // let itemText = data.awardList.find(item => item.itemValue == id).itemText
            //
            // data.diaForm.softState = itemText

        }

        let changeType = (id) => {
            // let itemText = data.technologyList.find(item => item.itemValue == id).itemText
            // data.diaForm.techClass = itemText
            /*          let itemText = data.technologyList.find((item) => item.itemValue == id).itemText;

                      data.diaForm.techClass = itemText;*/
        }


        let changeUnit = (item) => {

            data.diaForm.maintainUnitId = item.id

            data.diaForm.maintainUnit = item.name
        }




        let changeProgect = (id) => {

            // let itemText = data.projectList1.find(item => item.id == id).projectname
            //
            // data.diaForm.project = itemText

        }

        // 通过详情查询id

        let getDetail = async (id) => {
            data.detail_loading = true
            let res = await getDetailById(id);

            data.diaForm = res.data.data.info

            data.files = res.data.data.files

            data.changeLogs = res.data.data.changeLogs
            data.detail_loading = false
        };

        // 技术分类/软著状态===>数据字典

        let getCodeList = () => {

            getDictionary(['KJSL_BUSINESS_SECTOR', 'KJSL_SOFT_STATE']).then((res) => {

                data.technologyList = res.data.data.KJSL_BUSINESS_SECTOR;

                data.awardList = res.data.data.KJSL_SOFT_STATE;

            });
        };



        // 项目

        let getProjectList = () => {

            getProject({}).then((res) => {

                data.projectList1 = res.data.data;
            });
        };

        // 著作人

        let getWorkList = () => {

            getUser({}).then((res) => {

                data.workerList = res.data.data;
            });
        };

        // 单位
        let getUnitList = () => {

            getUnit({}).then((res) => {
                data.unitNameList = res.data.data;
            });
        };

        // 关闭清除对话框里面的数据,附件.变更记录也要删除

        let close = () => {
            data.files = []
            DiaForm.value.resetFields();
            emit("changeDialog");
            data.tabId = '1';
        };

        return {
            DiaForm,
            filesParams,
            rules,
            succeedApproval,
            changeState,
            changeType,
            changeUnit,
            changeProgect,
            getUnitList,
            getWorkList,
            getProjectList,
            getCodeList,
            ...toRefs(data),
            close,
            save,
            deptForm,
            open,
            handleCurrentChange,
            handleSizeChange,
            toHandle1,
            Visible,
            handleSelectionChange1,
            changeList,
            activeName,
            isShow,
            isProject,
            xiangmuParams,
            options,
            clearForm,



        };
    },
};
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: end;
}

:deep(.el-dialog__body) {
    display: none;
}

// 滚动条
:deep(.demo-tabs > .el-tabs__content) {
    max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.el-col .el-select {
    width: 120px;
    margin-right: 0px !important;
}
</style>
